<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>9-6</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        nav {
            position: fixed;
            top: 0;
            height: 50px;
            width: 100%;
            background-color: red;
            text-align: center;
        }
        
        .content {
            position: relative;
            height: 1000px;
            width: 70%;
            background-color: pink;
            text-align: center;
            margin: 0 auto;
            line-height: 300px;
        }
        
        section {
            position: fixed;
            height: 50px;
            width: 50px;
            background-color: yellow;
            top: 400px;
            left: 90%;
            display: none;
        }
    </style>
</head>

<body>

    <div class="content">内容区域</br>内容区域</div>
    <nav>导航栏</nav>
    <section>返回顶部</section>
    <script>
        var section = document.querySelector('section');
        document.addEventListener('scroll', function() {
            if (window.pageYOffset > 100) {
                section.style.display = 'block'
            } else {
                section.style.display = 'none';
            }

        })
        section.addEventListener('click', function() {
            move();
        })

        function move() {
            var flat = window.pageYOffset;
            var a = window.setInterval(function() {
                flat = flat - 1;
                window.scrollTo(0, flat);
                if (flat <= 0) {
                    clearInterval(a);
                }
            }, 30)
        }
        /* 定时器看作循环，再为循环添加时间，可以在该定时器内部用clearsetinterval停止 */
    </script>

</body>

</html>